package cn.schoolwow.quickdao.test.module.business.user.dml.json.flow.add;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Assert;

public class AddUserJSONProcessFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        singleInsert(flowContext);
        multipleInsert(flowContext);
    }

    @Override
    public String name() {
        return "插入用户信息-JSON格式";
    }

    private void singleInsert(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        JSONObject user = new JSONObject();
        user.put("username", "user0");
        user.put("password", "123456");
        user.put("email", "user0@fake.com");
        user.put("mobile", "12345678911");

        dao.addRecordString("插入单个用户");
        int effect = dao.insert("user", user);
        Assert.assertEquals(1, effect);
        user.put("id", user.getLong("generateKeys"));

        flowContext.putTemporaryData("insertUser", user);
    }

    private void multipleInsert(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        JSONArray insertUserList = new JSONArray();
        for(int i=1;i<=10;i++){
            JSONObject user = new JSONObject();
            user.put("username", "user"+i);
            user.put("password", "123456");
            user.put("email", "user"+i+"@fake.com");
            user.put("mobile", "12345678911");
            insertUserList.add(user);
        }

        dao.addRecordString("插入多个用户");
        int effect = dao.insert("user", insertUserList);
        Assert.assertEquals(10, effect);

        for(int i=0;i<insertUserList.size();i++){
            JSONObject user = insertUserList.getJSONObject(i);

            user.put("id", user.getLong("generateKeys"));
        }
        flowContext.putTemporaryData("insertUserList", insertUserList);
    }
}
